package Interfaz;
import javax.swing.text.MaskFormatter;
import java.util.Vector;
import java.util.Date;
import Modelo.*;
import ingredientsClient.Consumer;

import java.awt.Menu;
import java.awt.MenuBar;
import java.awt.MenuItem;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import javax.xml.ws.Endpoint;



public class HowToGui extends javax.swing.JFrame {

    private Vector<String> tags;
    private Vector<Author> authors;
    
    private Vector agregaPath = new Vector();
    private Vector agregaTitulo = new Vector();
    private Vector existePath = new Vector();
    private Vector existeTitulo = new Vector();
    private Vector revision = new Vector();
    
    private boolean modifying;
    private Recipe recipe;
    
    
    
    public HowToGui() {
        initComponents();
        
        tags = new Vector<String>();
        authors = new Vector<Author>();
        modifying = false;
        Util.readServer();
        //readDir();
        try{
            loadIngredients();
            loadList();
        }catch(Exception e){e.printStackTrace();}
    }
    
    private void loadModify(Recipe recipe){
        
        this.cleanUI();
        
        this.recipe = recipe;
        
        tags = recipe.getTags();
        authors = recipe.getAuthors();
        revision = recipe.getRevisions();
        
        jTxtTitulo.setText(recipe.getTitle());
        jTxtArea.setText(recipe.getAbstract());
        jBtnCrear.setText( "Modify" );
        modifying = true;
        //lo hice asi de inmundo ya q al cambiar de interfaz esto av a tener q estar implementado in other way
        Vector ing = recipe.getIngredients();
        for(int i = 0; i < ing.size(); i++){
            
            agregaPath.addElement(((Ingredient)ing.get(i)).getFileName());
            agregaTitulo.addElement(((Ingredient)ing.get(i)).getTitle());
            existeTitulo.remove(((Ingredient)ing.get(i)).getTitle());
            existePath.remove(((Ingredient)ing.get(i)).getFileName());
            
        }
        
        jListaAgregados.setListData(agregaTitulo);
        jListaTemas.setListData(existeTitulo);
    }
    
    private void saveDir(){
        File dir = new File("lib");
        File archivo;
        
        try{
            if(!dir.isDirectory()){
                dir.mkdir();
            }
            archivo = new File(dir, "config.how");
            FileOutputStream f = new FileOutputStream(archivo);
            DataOutputStream escribir = new DataOutputStream(f);
            
            escribir.writeUTF( Util.getIngredientsDirectory() );
        }catch(Exception e){}
    }
    
    //no hace nada..borrar later 
//    private void readDir(){
//        File archivo;
//        File dir = new File("lib");
//        
//        if(dir.isDirectory()){
//            try{
//                archivo = new File(dir, "config.how");
//                FileInputStream f = new FileInputStream(archivo);
//                DataInputStream leer = new DataInputStream(f);
//                
//                //Util.ingredientsDirectory = leer.readUTF();
//                System.out.println( Util.getIngredientsDirectory() );
//                //setIngredientsDirectory(leer.readUTF());
//            }catch(Exception e){
//                Util.errorDialog("Error", "No hay ninguna carpeta de Ingredientes seleccionada.");
//            }
//        }
//        else{
//            Util.errorDialog("Error", "No hay ninguna carpeta de Ingredientes seleccionada.");
//        }
//    }
    
    // <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents
    private void initComponents() {
        jPopupMenu1 = new javax.swing.JPopupMenu();
        jLabel1 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        jTxtTitulo = new javax.swing.JTextField();
        jLabel8 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTxtArea = new javax.swing.JTextArea();
        jSeparator2 = new javax.swing.JSeparator();
        jLabel3 = new javax.swing.JLabel();
        jScrollPane2 = new javax.swing.JScrollPane();
        jListaTemas = new javax.swing.JList();
        jLabel4 = new javax.swing.JLabel();
        jScrollPane3 = new javax.swing.JScrollPane();
        jListaAgregados = new javax.swing.JList();
        jLabel5 = new javax.swing.JLabel();
        jBtnAgregar = new javax.swing.JButton();
        jBtnQuitar = new javax.swing.JButton();
        jBtnCrear = new javax.swing.JButton();
        jBtnArriba = new javax.swing.JButton();
        jBtnAbajo = new javax.swing.JButton();
        bManageTags = new javax.swing.JButton();
        bManageAuthors = new javax.swing.JButton();
        jSeparator3 = new javax.swing.JSeparator();
        jMenuBar1 = new javax.swing.JMenuBar();
        mFile = new javax.swing.JMenu();
        mNew = new javax.swing.JMenuItem();
        mOpen = new javax.swing.JMenuItem();
        mSep1 = new javax.swing.JSeparator();
        mQuit = new javax.swing.JMenuItem();
        mActions = new javax.swing.JMenu();
        mPreferences = new javax.swing.JMenuItem();
        mIngredient = new javax.swing.JMenu();
        mNewIngredient = new javax.swing.JMenuItem();
        mOpenIngredient = new javax.swing.JMenuItem();
        mSearchIngredients = new javax.swing.JMenuItem();
        mView = new javax.swing.JMenu();
        mPreview = new javax.swing.JMenuItem();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Fresita");
        setFocusCycleRoot(false);
        addWindowFocusListener(new java.awt.event.WindowFocusListener() {
            public void windowGainedFocus(java.awt.event.WindowEvent evt) {
                formWindowGainedFocus(evt);
            }
            public void windowLostFocus(java.awt.event.WindowEvent evt) {
            }
        });
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowActivated(java.awt.event.WindowEvent evt) {
                formWindowActivated(evt);
            }
            public void windowClosing(java.awt.event.WindowEvent evt) {
                formWindowClosing(evt);
            }
        });
        addComponentListener(new java.awt.event.ComponentAdapter() {
            public void componentShown(java.awt.event.ComponentEvent evt) {
                formComponentShown(evt);
            }
        });
        addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                formFocusGained(evt);
            }
        });

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 16));
        jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel1.setText("Recipes builder");

        jLabel6.setFont(new java.awt.Font("Tahoma", 0, 12));
        jLabel6.setText("Title");

        jLabel8.setFont(new java.awt.Font("Tahoma", 0, 12));
        jLabel8.setText("Abstract");

        jTxtArea.setColumns(20);
        jTxtArea.setLineWrap(true);
        jTxtArea.setRows(5);
        jTxtArea.setWrapStyleWord(true);
        jScrollPane1.setViewportView(jTxtArea);

        jLabel3.setFont(new java.awt.Font("Tahoma", 1, 14));
        jLabel3.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel3.setText("Recipe's content");

        jListaTemas.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        jScrollPane2.setViewportView(jListaTemas);

        jLabel4.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel4.setText("Ingredients");

        jListaAgregados.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        jScrollPane3.setViewportView(jListaAgregados);

        jLabel5.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel5.setText("Recipe's ingredients");

        jBtnAgregar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/go-previous.png")));
        jBtnAgregar.setNextFocusableComponent(jBtnQuitar);
        jBtnAgregar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBtnAgregarActionPerformed(evt);
            }
        });

        jBtnQuitar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/list-remove.png")));
        jBtnQuitar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBtnQuitarActionPerformed(evt);
            }
        });

        jBtnCrear.setText("Create");
        jBtnCrear.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBtnCrearActionPerformed(evt);
            }
        });

        jBtnArriba.setFont(new java.awt.Font("Tahoma", 1, 12));
        jBtnArriba.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/go-up.png")));
        jBtnArriba.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBtnArribaActionPerformed(evt);
            }
        });

        jBtnAbajo.setFont(new java.awt.Font("Tahoma", 1, 12));
        jBtnAbajo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/go-down.png")));
        jBtnAbajo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBtnAbajoActionPerformed(evt);
            }
        });

        bManageTags.setText("Manage Tags");
        bManageTags.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bManageTagsActionPerformed(evt);
            }
        });

        bManageAuthors.setText("Manage Authors");
        bManageAuthors.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bManageAuthorsActionPerformed(evt);
            }
        });

        mFile.setText("File");
        mNew.setText("New");
        mNew.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                mNewActionPerformed(evt);
            }
        });

        mFile.add(mNew);

        mOpen.setText("Open");
        mOpen.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                mOpenActionPerformed(evt);
            }
        });

        mFile.add(mOpen);

        mFile.add(mSep1);

        mQuit.setText("Quit");
        mQuit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                mQuitActionPerformed(evt);
            }
        });

        mFile.add(mQuit);

        jMenuBar1.add(mFile);

        mActions.setText("Actions");
        mPreferences.setText("Configure server");
        mPreferences.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                mConfigureServerActionPerformed(evt);
            }
        });

        mActions.add(mPreferences);

        jMenuBar1.add(mActions);

        mIngredient.setText("Ingredients");
        mNewIngredient.setText("New");
        mNewIngredient.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                mNewIngredientActionPerformed(evt);
            }
        });

        mIngredient.add(mNewIngredient);

        mOpenIngredient.setText("Open");
        mOpenIngredient.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                mOpenIngredientActionPerformed(evt);
            }
        });

        mIngredient.add(mOpenIngredient);

        mSearchIngredients.setText("Search");
        mSearchIngredients.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                mSearchIngredientsActionPerformed(evt);
            }
        });

        mIngredient.add(mSearchIngredients);

        jMenuBar1.add(mIngredient);

        mView.setText("View");
        mPreview.setText("Preview");
        mPreview.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                mPreviewActionPerformed(evt);
            }
        });

        mView.add(mPreview);

        jMenuBar1.add(mView);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createSequentialGroup()
                            .addComponent(jSeparator3, javax.swing.GroupLayout.DEFAULT_SIZE, 531, Short.MAX_VALUE)
                            .addContainerGap())
                        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                            .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, 533, Short.MAX_VALUE)
                            .addGap(10, 10, 10))
                        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                .addComponent(jLabel3, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 531, Short.MAX_VALUE)
                                .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                        .addComponent(jBtnAbajo, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                        .addComponent(jBtnQuitar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                        .addComponent(jBtnArriba, javax.swing.GroupLayout.PREFERRED_SIZE, 89, javax.swing.GroupLayout.PREFERRED_SIZE))
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                        .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 160, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addComponent(jLabel5))
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                    .addComponent(jBtnAgregar, javax.swing.GroupLayout.PREFERRED_SIZE, 84, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                        .addGroup(layout.createSequentialGroup()
                                            .addComponent(jLabel4)
                                            .addGap(97, 97, 97))
                                        .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 168, javax.swing.GroupLayout.PREFERRED_SIZE))))
                            .addContainerGap())
                        .addGroup(layout.createSequentialGroup()
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                .addComponent(jSeparator2, javax.swing.GroupLayout.Alignment.LEADING)
                                .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                                    .addComponent(jLabel6)
                                    .addGap(35, 35, 35)
                                    .addComponent(jTxtTitulo, javax.swing.GroupLayout.PREFERRED_SIZE, 466, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                                    .addComponent(jLabel8)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                    .addComponent(jScrollPane1))
                                .addGroup(layout.createSequentialGroup()
                                    .addComponent(bManageAuthors, javax.swing.GroupLayout.PREFERRED_SIZE, 167, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                    .addComponent(bManageTags, javax.swing.GroupLayout.PREFERRED_SIZE, 173, javax.swing.GroupLayout.PREFERRED_SIZE)))
                            .addContainerGap(17, Short.MAX_VALUE)))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(jBtnCrear, javax.swing.GroupLayout.PREFERRED_SIZE, 168, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addContainerGap())))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addGap(19, 19, 19)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel6)
                    .addComponent(jTxtTitulo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel8)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 46, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(bManageTags)
                    .addComponent(bManageAuthors))
                .addGap(17, 17, 17)
                .addComponent(jSeparator2, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel3)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addGroup(layout.createSequentialGroup()
                                    .addComponent(jLabel4)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                    .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addGroup(layout.createSequentialGroup()
                                    .addComponent(jLabel5)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                    .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addComponent(jBtnAgregar)
                                .addGap(60, 60, 60))))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(42, 42, 42)
                        .addComponent(jBtnArriba)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jBtnQuitar)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jBtnAbajo)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 31, Short.MAX_VALUE)
                .addComponent(jSeparator3, javax.swing.GroupLayout.PREFERRED_SIZE, 2, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jBtnCrear)
                .addContainerGap())
        );
        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-555)/2, (screenSize.height-483)/2, 555, 483);
    }// </editor-fold>//GEN-END:initComponents

    private void mPreviewActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mPreviewActionPerformed
        String path = Util.selectPath(3);
        
        File file = new File(path);
        
        Util.transformar(file);
    }//GEN-LAST:event_mPreviewActionPerformed

    private void formWindowActivated(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowActivated
        this.reload();
    }//GEN-LAST:event_formWindowActivated

    private void mQuitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mQuitActionPerformed
        System.exit( 0 );
    }//GEN-LAST:event_mQuitActionPerformed

    private void mOpenIngredientActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mOpenIngredientActionPerformed
        String directory = Util.selectPath(1);
        String how = Util.readTextFile(directory);
        Ingredient ingredient = Ingredient.fromXml(how);
        IngredientsGui ingredientGui = new IngredientsGui(ingredient);
        ingredientGui.setVisible(true);
    }//GEN-LAST:event_mOpenIngredientActionPerformed

    private void mNewActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mNewActionPerformed
        reload();
        tags.removeAllElements();
        agregaPath.removeAllElements();
        agregaTitulo.removeAllElements();
        jListaAgregados.setListData(agregaTitulo);
        
        this.reload();

        jTxtArea.setText("");
        jTxtTitulo.setText("");
        jBtnCrear.setText( "Create" );
    }//GEN-LAST:event_mNewActionPerformed

    private void mOpenActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mOpenActionPerformed
        String path = Util.selectPath(Util.PATH_HOWTO_DIR);
        String how = Util.readTextFile( path );
        Recipe recipe = Recipe.fromXml(how);
        loadModify(recipe);
    }//GEN-LAST:event_mOpenActionPerformed
    private void reload(){
        loadIngredients();
        filter();
        loadList();
    }
    private void filter(){
        for(int i = 0; i < agregaTitulo.size(); i++){
            existeTitulo.remove((String)agregaTitulo.get(i));
            existePath.remove((String)agregaPath.get(i));
        }
        jListaAgregados.setListData(agregaTitulo);
        jListaTemas.setListData(existeTitulo);
    }
    
    private void mConfigureServerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mConfigureServerActionPerformed
        ConfigureServerDialog csd = new ConfigureServerDialog(this, true);
        if(Util.getServer() != null){
            csd.setServer(Util.getServer());
        }
        csd.setVisible(true);
        
        if( csd.isSuccess() )
        {
            Util.setServer(csd.getServer());
        }
    }//GEN-LAST:event_mConfigureServerActionPerformed

    private void mNewIngredientActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mNewIngredientActionPerformed
        WizardIngredientGui ingredient = new WizardIngredientGui();
        ingredient.setVisible(true);
    }//GEN-LAST:event_mNewIngredientActionPerformed

    private void mSearchIngredientsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mSearchIngredientsActionPerformed
        SearchGui search = new SearchGui(this, true, existePath, existeTitulo);
        search.setVisible(true);
        jListaTemas.setListData(existeTitulo);
    }//GEN-LAST:event_mSearchIngredientsActionPerformed

    private void bManageAuthorsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bManageAuthorsActionPerformed
        NewAuthorsDialog authorsDialog = new NewAuthorsDialog( this, true );
        authorsDialog.setAuthors( authors );
        authorsDialog.setVisible( true );
        
        if( authorsDialog.isSuccess() )
        {
            authors = authorsDialog.getAuthors();
        }     
    }//GEN-LAST:event_bManageAuthorsActionPerformed

    private void bManageTagsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bManageTagsActionPerformed
        
        NewTagsDialog tagDialog = new NewTagsDialog( this, true );
        tagDialog.setTags( tags );
        tagDialog.setVisible( true );
        
        if( tagDialog.isSuccess() )
        {
            tags = tagDialog.getTags();
        }
    }//GEN-LAST:event_bManageTagsActionPerformed

    private void formComponentShown(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentShown
        this.reload();
    }//GEN-LAST:event_formComponentShown

    private void formWindowGainedFocus(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowGainedFocus
        
    }//GEN-LAST:event_formWindowGainedFocus

    private void formFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_formFocusGained

    }//GEN-LAST:event_formFocusGained

    private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
       
    }//GEN-LAST:event_formWindowClosing
    
    public void loadRecipe(Recipe recipe){
        
        jTxtTitulo.setText(recipe.getTitle());
        jTxtArea.setText(recipe.getAbstract());
        
        tags = recipe.getTags();
        authors = recipe.getAuthors();
        revision = recipe.getRevisions();
        
       
        Vector ingredients = recipe.getIngredients();
        //aca un metodo que carge los agregados pero sacandolos de la lista de Existe asi queda consistente
        
    }
    
    private void loadIngredients(){
        File[] ingredients = Util.getIngredients();
        existePath.removeAllElements();
        existeTitulo.removeAllElements();
        if(ingredients == null){
            return ;
        }
        try{
            for(int i = 0; i < ingredients.length ; i++){
        
                existePath.add(ingredients[i].getAbsolutePath());
            
                String ingredientXML = Util.readTextFile(ingredients[i].getAbsolutePath());
            
                Ingredient ing = Ingredient.fromXml(ingredientXML); 
            
                existeTitulo.add(ing.getTitle());
            }
        }catch(NullPointerException e){
            //Util.errorDialog("Error", "No hay ingredientes creados.");
            e.printStackTrace();
        }
        
    }
    
    
    
    private void loadList(){
        jListaTemas.removeAll();
        jListaTemas.setListData(existeTitulo);
    }
    
    private void cleanUI(){
        jTxtTitulo.setText("");
        jTxtArea.setText("");
        tags.removeAllElements();
        authors.removeAllElements();
        jListaAgregados.removeAll();
        existeTitulo.removeAllElements();
        existePath.removeAllElements();
        agregaTitulo.removeAllElements();
        agregaPath.removeAllElements();
        
        this.loadIngredients();
        this.loadList();
    }
    
    public Revision newRevision( int revisionNumber )
    {
        CreateRevision createRevision = new CreateRevision( this, true, revisionNumber, new java.util.Date() );
        createRevision.setVisible( true );
        return createRevision.getRevision();
    }
        
    private void jBtnCrearActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBtnCrearActionPerformed
        Date d = new Date();
        
        int rev = 1;
        
        if( this.modifying )
        {
            rev = recipe.getRevision() + 1;
        }
        
        if(authors.size() == 0){
            Util.errorDialog("Error", "No authors");
            return;
        }
        if(jTxtTitulo.getText().compareTo("") == 0){
            Util.errorDialog("Error", "No title");
            return;
        }
        if(jTxtArea.getText().compareTo("") == 0){
            Util.errorDialog("Error", "No abstract");
            return;
        }
        if(tags.size() == 0){
            Util.errorDialog("Error", "No tags ");
            return;
        }
        
        Vector ingredients = Ingredient.getIngredientsByFileName(agregaPath);
        //Vector ingredients = new Vector();
        Recipe recipe = new Recipe(jTxtTitulo.getText(), authors,(int)d.getTime(),tags,jTxtArea.getText(),revision, ingredients, rev );
        
        if( this.modifying )
        {
            Revision r = newRevision( rev );
            
            if( r == null )
            {
                Modelo.Util.errorDialog( "Error", "A revision must be created to save the modifications" );
                return;
            }
            
            recipe.addRevision( r );
        }
        
        String path = Util.getHowtosDirectory();
        
        if ( !path.equalsIgnoreCase("") )
        {
            recipe.save();
            Util.informDialog( "Archivo Guardado" , "El archivo " + recipe.getFileName() + " fue guardado con exito" );
        }
        
        for(int i=0;i<ingredients.size();i++){
            Ingredient ingredient = (Ingredient) ingredients.get(i);
            
            File fiIngre = new File( ingredient.getFileName() );
            FileXML fxml = new FileXML( fiIngre );

            Consumer c = new Consumer();
            if( !c.sendFile( Util.node2String( fxml.toXml() ), false ) ){
                Util.errorDialog( "Connection Failed", "Ingredient/s cannot be uploaded." );
            }
        }
        
        
        File fiRecipe = new File( recipe.getFileName() );
        FileXML fxml = new FileXML( fiRecipe );
        
        Consumer c = new Consumer();
        if( !c.sendFile( Util.node2String( fxml.toXml() ), true ) ){
            Util.errorDialog( "Connection Failed", "The new Recipe cannot be uploaded." );
        }
        
        
        this.cleanUI();
    }//GEN-LAST:event_jBtnCrearActionPerformed
    
    
    private void jBtnAbajoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBtnAbajoActionPerformed
        try{
            String t1 = (String) agregaTitulo.get(jListaAgregados.getSelectedIndex());
            String p1 = (String) agregaPath.get(jListaAgregados.getSelectedIndex());
            
            String t2 = (String) agregaTitulo.get(jListaAgregados.getSelectedIndex()+1);
            String p2 = (String) agregaPath.get(jListaAgregados.getSelectedIndex()+1);
            
            agregaTitulo.setElementAt(t2, jListaAgregados.getSelectedIndex());
            agregaTitulo.setElementAt(t1, jListaAgregados.getSelectedIndex()+1);
            
            agregaPath.setElementAt(p2, jListaAgregados.getSelectedIndex());
            agregaPath.setElementAt(p1, jListaAgregados.getSelectedIndex()+1);

            int nuevoIndex  = jListaAgregados.getSelectedIndex()+1;
            
            jListaAgregados.removeAll();
            jListaAgregados.setListData(agregaTitulo);
            jListaAgregados.setSelectedIndex(nuevoIndex);
            
        }catch(Exception e){}
    }//GEN-LAST:event_jBtnAbajoActionPerformed

    private void jBtnArribaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBtnArribaActionPerformed
        try{
            String t1 = (String) agregaTitulo.get(jListaAgregados.getSelectedIndex());
            String p1 = (String) agregaPath.get(jListaAgregados.getSelectedIndex());
            
            String t2 = (String) agregaTitulo.get(jListaAgregados.getSelectedIndex()-1);
            String p2 = (String) agregaPath.get(jListaAgregados.getSelectedIndex()-1);
            
            agregaTitulo.setElementAt(t2, jListaAgregados.getSelectedIndex());
            agregaTitulo.setElementAt(t1, jListaAgregados.getSelectedIndex()-1);
            
            agregaPath.setElementAt(p2, jListaAgregados.getSelectedIndex());
            agregaPath.setElementAt(p1, jListaAgregados.getSelectedIndex()-1);
            
            int nuevoIndex = jListaAgregados.getSelectedIndex()-1;
            
            jListaAgregados.removeAll();
            jListaAgregados.setListData(agregaTitulo);
            jListaAgregados.setSelectedIndex(nuevoIndex);
        }catch(Exception e){}
    }//GEN-LAST:event_jBtnArribaActionPerformed

    private void jBtnQuitarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBtnQuitarActionPerformed
        try{
            existeTitulo.addElement(agregaTitulo.get(jListaAgregados.getSelectedIndex()));
            existePath.addElement(agregaPath.get(jListaAgregados.getSelectedIndex()));
            jListaTemas.setListData(existeTitulo);
            agregaTitulo.remove(jListaAgregados.getSelectedIndex());
            agregaPath.remove(jListaAgregados.getSelectedIndex());
            jListaAgregados.removeAll();
            jListaAgregados.setListData(agregaTitulo);
        }catch(ArrayIndexOutOfBoundsException e){}
                
    }//GEN-LAST:event_jBtnQuitarActionPerformed

    private void jBtnAgregarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBtnAgregarActionPerformed
      
        try{
            agregaTitulo.addElement(existeTitulo.get(jListaTemas.getSelectedIndex()));
            agregaPath.addElement(existePath.get(jListaTemas.getSelectedIndex()));
            jListaAgregados.setListData(agregaTitulo);
            existeTitulo.remove(jListaTemas.getSelectedIndex());
            existePath.remove(jListaTemas.getSelectedIndex());
            jListaTemas.removeAll();
            jListaTemas.setListData(existeTitulo);
        }catch(ArrayIndexOutOfBoundsException e){}
    }//GEN-LAST:event_jBtnAgregarActionPerformed

    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                HowToGui htg = new HowToGui();
                htg.setVisible(true);
                
                //String wsAddress = "http://localhost:1234/Gpi/Service";
                //Endpoint.publish(wsAddress, new Service(htg.getDatabase()));
                //System.out.println("Web service was published successfuly.\n" + "WSDL URL: "+wsAddress+"?WSDL");
            }
        });
    }
    
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton bManageAuthors;
    private javax.swing.JButton bManageTags;
    private javax.swing.JButton jBtnAbajo;
    private javax.swing.JButton jBtnAgregar;
    private javax.swing.JButton jBtnArriba;
    private javax.swing.JButton jBtnCrear;
    private javax.swing.JButton jBtnQuitar;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JList jListaAgregados;
    private javax.swing.JList jListaTemas;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JPopupMenu jPopupMenu1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JSeparator jSeparator2;
    private javax.swing.JSeparator jSeparator3;
    private javax.swing.JTextArea jTxtArea;
    private javax.swing.JTextField jTxtTitulo;
    private javax.swing.JMenu mActions;
    private javax.swing.JMenu mFile;
    private javax.swing.JMenu mIngredient;
    private javax.swing.JMenuItem mNew;
    private javax.swing.JMenuItem mNewIngredient;
    private javax.swing.JMenuItem mOpen;
    private javax.swing.JMenuItem mOpenIngredient;
    private javax.swing.JMenuItem mPreferences;
    private javax.swing.JMenuItem mPreview;
    private javax.swing.JMenuItem mQuit;
    private javax.swing.JMenuItem mSearchIngredients;
    private javax.swing.JSeparator mSep1;
    private javax.swing.JMenu mView;
    // End of variables declaration//GEN-END:variables
    
}
